$(function(){
	
	var supplierId = $(".supplierId").val();
	var warehouseId;
	var cartGoods;
	var totalAmount = 0;
	$(".form-group #amount").text(totalAmount);
	
	$('.datepicker').datepicker({
	     format: "yyyy-mm-dd",
	     language: "zh-CN",
	     orientation: "top left",
	     autoclose:true
	});
	$('.purchaseDate').val(new Date().Format("yyyy-MM-dd"));
	var dataTable = $('#supplierGoods').dataTable({
		"ColumnDefs" : [ {
	        sDefaultContent : '',
	        aTargets : [ '_all' ]
		} ],
		"bPaginate": false,
		bFilter: false,
        aaData: [],
        aoColumns: [
            {mDataProp:"taosku"},
            {mDataProp:"bn"},
            {mDataProp:"name"},
            {mDataProp:"deliveryNum"},
            {mDataProp:"availableNum"},
            {mDataProp:"saleNumPerWeek"},
            {mDataProp:"salePrice"},
            {mDataProp:"recentPurchasePrice"},
            {mDataProp:"purchasePrice"},
            {mDataProp:"discountRate"},
            {mDataProp:"taxRate"},
            {mDataProp:"sizeSpec"},
            {mDataProp:"purchaseNum"},
            {mDataProp:"totalAmount"},
            {mDataProp:"goodsId"},
            {mDataProp:"goodsSpecId"}
        ],
        columnDefs:[{
        	targets:[8],
        	data:"purchasePrice",
        	render: function(data, type, full) {
                return "<input type='text' class='price userEdit' value="+ data+">";
            }
        },
        {
        	targets:[9],
        	data:"discountRate",
        	render: function(data, type, full) {
                return "<input type='text' class='rate userEdit' value='100'>";
            }
        } ,
        {
        	targets:[12],
        	data:"purchaseNum",
        	render: function(data, type, full) {
                return "<input type='text' class='buyAmount userEdit'  value=0>";
            }
        },
        {
        	targets:[13],
        	data:"totalAmount",
        	sClass:'amount',
        },
        {
        	targets:[14],
        	"bVisible": false,
        	data:"goodsId",
        },
        {
        	targets:[15],
        	"bVisible": false,
        	data:"goodsSpecId",
        }]
    } );
	$(".warehouseSelect").change(function(){
		warehouseId = $(this).val();
		if(warehouseId==-1){
			return false;
		}
		cartGoods = sessionStorage.getItem("LKT-CART"+warehouseId);
		if(cartGoods){
			cartGoods = JSON.parse(sessionStorage.getItem("LKT-CART"+warehouseId));
			//TODO
			initTable();
		}
		else{
			cartGoods = {};
		}
		RefreshTable("#supplierGoods","supplierGoods?warehouseId="+warehouseId+"&supplierId="+supplierId);
	});
	
	var selectGoodsTable = $('.selectGoods').dataTable({
		"ColumnDefs" : [ {
	        sDefaultContent : '',
	        aTargets : [ '_all' ]
		} ],
		bFilter: false,
		"bPaginate": false,
        aaData: [],
        aoColumns: [
            {mDataProp:"taosku"},
            {mDataProp:"taosku"},
            {mDataProp:"bn"},
            {mDataProp:"goodsName"},
            {mDataProp:"taxPrice"},
            {mDataProp:"taxPrice"},
            {mDataProp:"purchaseDate"},
            {mDataProp:"receiveNum"},
//            {mDataProp:"recentPurchasePrice"},
//            {mDataProp:"purchasePrice"},
//            {mDataProp:"discountRate"},
//            {mDataProp:"taxRate"},
//            {mDataProp:"sizeSpec"},
//            {mDataProp:"purchaseNum"},
//            {mDataProp:"totalAmount"}
        ],
        columnDefs:[{
        	targets:[0],
        	data:"taosku",
        	render: function(data, type, full) {
                return "<input type='checkbox' class='checkGoods' data-taosku='"+data+"'>";
            }
        }]
    } );
	
	
	//change display of button
	$(".chooseRelative").hide();
	$(".clearRelative").click(function(){
			displayToggle($(this));
			displayToggle($(".chooseRelative"));
			dataTable.fnClearTable();
	});
	$(".chooseRelative").click(function(){
			if(!warehouseId){
				alert("请选择仓库");
				return false;
			}
			displayToggle($(this));
			displayToggle($(".clearRelative"));
			
			RefreshTable("#supplierGoods","supplierGoods?warehouseId="+warehouseId+"&supplierId="+supplierId);
	});
	//
	$("#supplierGoods").on("change",".userEdit",function(){
		console.log($(this).val());
		var value = $(this).val();
		if(isNaN(value) || value<0)
		{
			alert("请输入正确数字！");
			return false;
		}
		var row = $(this).parents("tr");
		var price = row.find('.price').val();
		var buyAmount = row.find('.buyAmount').val();
		computeTotalAmount(row);
		var totalAmount = parseFloat(row.find('.amount').text());
		var rate = parseFloat(row.find('.rate').val())/100;
		var aData = dataTable.fnGetData($(row)); // get datarow
		
         if (null != aData && totalAmount && totalAmount!==0)  // null if we clicked on title row
         {
        	 aData['purchaseNum'] = value;
             var goods = new GoodsDetail(aData['goodsId'],aData['goodsSpecId'],aData['taosku'],aData['bn'],aData['name'],0
             ,price,buyAmount,totalAmount,0,rate);
             cartGoods[aData['goodsId']] = goods;
         }
	});
	
	function getOrderValue(){
		var payType=$(".payType").val();
		var prepayAmount=$(".prepayAmount").val();
		var discountAmount = $(".discountAmount").val();
		var planDate = $(".planDate").val();
		var purchaseDate = $(".purchaseDate").val();
		var address = $("#address").val();
		var demo = $("#demo").val();
		var submitOrder = {};
		submitOrder.settmentType=payType;
		submitOrder.prepayAmount=prepayAmount ;
		submitOrder.discount=parseFloat(discountAmount) ;
		submitOrder.planArrivetime=planDate;
		submitOrder.createTime=purchaseDate;
		submitOrder.address=address;
		submitOrder.remark=demo;
		submitOrder.supplierId = supplierId;
		submitOrder.warehouseId = warehouseId;
		var details = [];
		for(var p in cartGoods){
			if(cartGoods.hasOwnProperty(p)){
				details.push(cartGoods[p]);
			}
		}
		submitOrder.details = details;
		submitOrder = JSON.stringify(submitOrder);
		return submitOrder;
	}
	
	$(".submitOrder").click(function(){
		var data = getOrderValue();
		$.ajax({
			url:"submitPurchaseOrder",
			type:'post',
			data:data,
			contentType: "application/json; charset=utf-8",
			dataType:"json",
			success:function(data){
				alert("下单成功！");
				var href = "purchaseOrderDetail?supplierId="+ supplierId+"&supplierName="+ $("#supplierName").val().replace(/\s+/g,"");
				$(".wrapper-content").load(href);
			},
			error:function(){
				
			}
		});
	});
	
	$(".searchPriceHistory").click(function(){
		var bn = $("#bn").val();
		var name = $("#goodsName").val();
		var taosku = $("#taosku").val();
		RefreshTable(".selectGoods","goods/purchaseHistory?goodsName="+name+"&bn="+bn+"&supplierId="+supplierId+"&warehouseId="+warehouseId+"&taosku="+taosku);
//		$.ajax({
//			url:"po_purchase/goods/purchaseHistory?goodsName="+name+"&bn="+bn+"&taosku="+taosku,
//			type:"get",
//			data:{},
//			success:function(data){
//				if(!data){
//					alert("查不到您所需要的商品！");
//				}
//				else{
//					
//				}
//			}
//		});
		
	});
	$(".addGoods").click(function(){
		var taoskuList = [];
		$.each($(".checkGoods"),function(i,e){
			if(e.checked){
				taoskuList.push($(e).data("taosku"));
			}
		});
		var data = {
				"taosku":taoskuList,
				"warehouseId":warehouseId,
				"supplierId":supplierId
			};
		data = JSON.stringify(data);
		$.ajax({
			url:"addGoodsToPurchaseOrder",
			data:data,
			contentType: "application/json; charset=utf-8",
			dataType:"json",
			type:"post",
			success:function(data){
				if(data && data.length !==0){
					$.each(data,function(i,e){
						$("#supplierGoods").DataTable().row.add({
							"taosku":e["taosku"],
							"bn":e["bn"],
							"name":e["goodsName"],
							"deliveryNum":e["deliveryNum"],
							"availableNum":e["availableNum"],
							"saleNumPerWeek":e["saleNumPerWeek"],
							"salePrice":e["salePrice"],
							"recentPurchasePrice":e["recentPurchasePrice"],
							"purchasePrice":e["purchasePrice"],
							"discountRate":e["discountRate"],
							"taxRate":e["taxRate"],
							"sizeSpec":e["sizeSpec"],
							"purchaseNum":e["purchaseNum"],
							"totalAmount":e["goodsAmount"],
							"goodsId":e['goodsId'],
							"goodsSpecId":e['specId']
						}).draw( false );
					});
				}
			}
		});
		$('#myModal').modal('hide');
	});
	$(".checkAll").change(function(){
		var value = this.checked;
		$.each($('.checkGoods'),function(i,e){
			e.checked = value;
		});
	});
	$(window).unload(saveToSessionStorage);
	function saveToSessionStorage(){
		sessionStorage.setItem('LKT-CART'+warehouseId,JSON.stringify(cartGoods));
	}
	function displayToggle($e){
		if($e.is(':hidden')){
			$e.show();
		}
		else{
			$e.hide();
		}
	}
	function RefreshTable(tableId, urlData)
    {
      //Retrieve the new data with $.getJSON. You could use it ajax too
      $.getJSON(urlData, null, function( json )
      {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i=0; i<json.data.length; i++)
        {
          table.oApi._fnAddData(oSettings, json.data[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
      });
    }
	function GoodsDetail(goodsId,goodsSpecId,taosku,bn,goodsName,isGift,taxPrice,orderNumber,taxAmount,receiveNumber,discountRate){
		var obj = {};
		obj.goodsId = goodsId;
		obj.goodsSpecId = goodsSpecId;
		obj.taosku = taosku;
		obj.bn = bn;
		obj.goodsName = goodsName;
		obj.isGift = isGift;
		obj.taxPrice = taxPrice;
		obj.orderNumber = orderNumber;
		obj.taxAmount = taxAmount;
		obj.receiveNumber = receiveNumber;
		obj.discountRate = discountRate;
		return obj;
	}
	function initTable(){
		
	}
	function computeTotalAmount($row){
		var total = parseFloat($row.find('.price').val())*parseFloat($row.find('.rate').val())*parseInt($row.find('.buyAmount').val())/100;
		$row.find('.amount').text(total);
		totalAmount+=total;
		$(".form-group #amount").text(totalAmount);
	}

});
